import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

class SwiperDemo extends StatefulWidget {
  @override
  _SwiperDemoState createState() => _SwiperDemoState();
}

class _SwiperDemoState extends State<SwiperDemo> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      width: MediaQuery.of(context).size.width,
      alignment: Alignment.center,
      child: Column(
        children: [
          Container(
            height: 150,
            child: Swiper(
              scrollDirection: Axis.horizontal,
              itemBuilder: _swiperBuilder,
              itemCount: 5,
              pagination: new SwiperPagination(
                  builder: DotSwiperPaginationBuilder(
                color: Colors.black54,
                activeColor: Colors.white,
              )),
              control: new SwiperControl(),
              autoplay: true,
              onTap: (index) => print('点击了第$index个'),
            ),
          ),
          Container(
            height: 120,
            child: Swiper(
              scrollDirection: Axis.horizontal,
              itemBuilder: _swiperBuilder,
              itemCount: 5,
              pagination: new SwiperPagination(
                  builder: DotSwiperPaginationBuilder(
                color: Colors.black54,
                activeColor: Colors.white,
              )),
              control: new SwiperControl(),
              autoplay: true,
              onTap: (index) => print('点击了第$index个'),
            ),
          ),
          Container(
            height: 150,
            child: Swiper(
              scrollDirection: Axis.horizontal,
              itemBuilder: _swiperBuilder,
              itemCount: 5,
              pagination: new SwiperPagination(
                  builder: DotSwiperPaginationBuilder(
                color: Colors.black54,
                activeColor: Colors.white,
              )),
              control: new SwiperControl(),
              autoplay: true,
              onTap: (index) => print('点击了第$index个'),
            ),
          ),
        ],
      ),
    );
  }

  Widget _swiperBuilder(BuildContext context, int index) {
    return (
        //Image.network("https://i0.hdslb.com/bfs/feed-admin/1fae7c89e9ce7ed8de3d0740afbc0db2080d76fd.jpg@880w_388h_1c_95q", fit: BoxFit.fitHeight)
        CachedNetworkImage(
          imageUrl: "https://i0.hdslb.com/bfs/feed-admin/1fae7c89e9ce7ed8de3d0740afbc0db2080d76fd.jpg@880w_388h_1c_95q",
          placeholder: (context, url) => LinearProgressIndicator(),
          errorWidget: (context, url, error) => Icon(Icons.error),
        )
    );
  }

  @override
  bool get wantKeepAlive => true;
}
